import os
import subprocess
import matplotlib.pyplot as plt


def save2emf(fig_path, group_name, bsave=True):
    if not bsave:
        return

    group_name = group_name.replace(' ', '').replace('(', '[').replace(')', ']')
    svg_file = os.path.join(fig_path, f'{group_name}.svg')
    emf_file = os.path.join(fig_path, f'{group_name}.emf')
    print(f'Saving figure to {emf_file} ...')

    plt.savefig(svg_file)
    # emf_file = svg_file[0:-3] + 'emf'

    cmd = f'inkscape -z {svg_file} -M "{emf_file}"'
    process = subprocess.Popen(cmd,
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    for line in process.stdout:
        print(line)

    os.remove(svg_file)

    print('Done!')
    if process.returncode:
        raise Exception('cmd %s failed, see above for details', cmd)


# %%
# import numpy as np
# import matplotlib.pyplot as plt
#
# X = np.linspace(-10, 10, 100)
# y = np.sin(X)
#
# plt.figure()
# plt.plot(X, y)
# plt.xlabel('$X$')
# plt.ylabel('$y$')
# plt.annotate('$y=\sin X$', xy=(1, 0), xytext=(0, 0))
# plt.savefig('sinx.svg')
# svg2emf('sinx.svg')
